package diploma.kisel.modelas.service;

import java.util.List;
import java.util.Set;

import javax.persistence.NoResultException;

import diploma.kisel.modelas.domain.Role;
import diploma.kisel.modelas.domain.User;
import diploma.kisel.modelas.repository.UserRepositoryImpl;
import diploma.kisel.modelas.repository.api.RoleRepository;
import diploma.kisel.modelas.repository.api.UserRepository;
import diploma.kisel.modelas.service.api.RoleService;
import diploma.kisel.modelas.service.api.UserService;

public class UserServiceImpl implements UserService {

	private UserRepository userRepository = new UserRepositoryImpl();
	private RoleService roleService = new RoleServiceImpl(); 

	@Override
	public List<User> findAll() {
		return userRepository.findAll();
	}

	@Override
	public User findById(String login) {
		if (login != null)
			return userRepository.findById(login);
		return null;
	}

	@Override
	public User save(User user) {
		if (user != null)
			return userRepository.save(user);
		return null;
	}

	@Override
	public User update(User user) {
		return userRepository.update(user);
	}

	@Override
	public void remove(User user) {
		if (user.getLogin() != null)
			userRepository.remove(user);

	}

	@Override
	public void remove(String login) {
		User user = userRepository.findById(login);
		userRepository.remove(user);
	}

	@Override
	public boolean checkPassword(String login, String password) {
		boolean result = false;
		try {
			User user = userRepository.findById(login);
			if (user.getPassword().equals(password))
				result = true;
		} catch (NoResultException e) {

		}
		return result;
	}
	
	public boolean checkRole(User user, String nameRole) {
		Role role = roleService.findById(nameRole);
		Set<Role> roles = user.getRoles();
		if (roles.contains(role))
			return true;
		else
			return false;
 	}

}
